<template>
  <div class="flex-center login-container">
    <div class="left-content">
      <div>欢迎使用</div>
      <div class="fw-600">人工智能应用评价平台</div>
    </div>
    <div class="right-content">
      <div class="form-title fw-600">请使用账号密码登录</div>
      <el-form
        v-show="getShow"
        ref="formLogin"
        :model="loginData.loginForm"
        :rules="LoginRules"
        class="login-form"
        label-position="top"
        label-width="30px"
        :hide-required-asterisk="true"
        size="large"
      >
      <el-form-item prop="username" class="login-form-item">
        <template #label>
          <span class="flex-center">
            <Icon class="mr-5px" color="#009D85" icon="ep:user" />
            <span>账号</span>
          </span>
        </template>
        <el-input
          v-model="loginData.loginForm.username"
          :placeholder="t('login.usernamePlaceholder')"
        />
      </el-form-item>
      <el-form-item prop="password" class="login-form-item">
        <template #label>
            <span class="flex-center">
              <Icon class="mr-5px" color="#009D85" icon="ep:lock" />
              <span>密码</span>
            </span>
          </template>
        <el-input
          v-model="loginData.loginForm.password"
          :placeholder="t('login.passwordPlaceholder')"
          show-password
          type="password"
          @keyup.enter="handleLogin"
        />
      </el-form-item>
      <el-form-item>
        <XButton
          :loading="loginLoading"
          :title="t('login.login')"
          class="w-[100%]"
          type="primary"
          @click="handleLogin"
        />
      </el-form-item>
      <el-form-item>
        <XButton
          title="重置"
          class="w-[100%]"
          type="primary"
          plain
          @click="resetForm"
        />
      </el-form-item>
      </el-form>
    </div>
  </div>
  
</template>
<script lang="ts" setup>
import type { RouteLocationNormalizedLoaded } from 'vue-router'

import * as authUtil from '@/utils/auth'
import { usePermissionStore } from '@/store/modules/permission'
import * as LoginApi from '@/api/login'
import { LoginStateEnum, useFormValid, useLoginState } from './useLogin'

defineOptions({ name: 'LoginFormGw' })

const { t } = useI18n()
const formLogin = ref()
const { validForm } = useFormValid(formLogin)
const { getLoginState } = useLoginState()

const { currentRoute, push } = useRouter()
const permissionStore = usePermissionStore()
const redirect = ref<string>('')
const loginLoading = ref(false)
const getShow = computed(() => unref(getLoginState) === LoginStateEnum.LOGIN)

const LoginRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}
const loginData = reactive({
  isShowPassword: false,
  loginForm: {
    tenantName: '',
    username: '',
    password: '',
    rememberMe: false // 默认记录我。如果不需要，可手动修改
  }
  // loginForm: {
  //   tenantName: '冠图科技',
  //   username: 'admin',
  //   password: 'admin123',
  //   rememberMe: true // 默认记录我。如果不需要，可手动修改
  // }
})

// 记住我
const getLoginFormCache = () => {
  const loginForm = authUtil.getLoginForm()
  if (loginForm) {
    loginData.loginForm = {
      ...loginData.loginForm,
      username: loginForm.username ? loginForm.username : loginData.loginForm.username,
      password: loginForm.password ? loginForm.password : loginData.loginForm.password,
    }
  }
}
// 根据域名，获得租户信息
const getTenantByWebsite = async () => {
  const website = location.host
  const res = await LoginApi.getTenantByWebsite(website)
  if (res) {
    loginData.loginForm.tenantName = res.name
    authUtil.setTenantId(res.id)
  }
}
// const loading = ref() // ElLoading.service 返回的实例
// 登录
const handleLogin = async () => {
  loginLoading.value = true
  try {
    const data = await validForm()
    if (!data) return
    const res = await LoginApi.login(loginData.loginForm)
    if (!res) {
      return
    }
    authUtil.removeLoginForm()
    authUtil.setToken(res)
    if (!redirect.value) {
      redirect.value = '/'
    }
    push({ path: redirect.value || permissionStore.addRouters[0].path })
  } finally {
    loginLoading.value = false
    // loading.value.close()
  }
}
const resetForm = () => {
  loginData.loginForm = {
      ...loginData.loginForm,
      username: '',
      password: '',
    }
}
watch(
  () => currentRoute.value,
  (route: RouteLocationNormalizedLoaded) => {
    redirect.value = route?.query?.redirect as string
  },
  {
    immediate: true
  }
)
onMounted(() => {
  getLoginFormCache()
  getTenantByWebsite()
})
</script>

<style lang="scss" scoped>
.login-container {
  height: 100%;
  .left-content {
    color: var(--el-color-primary);
    font-size: 48px;
    line-height: 86px;
  }
  .right-content {
    width: 376px;
    height: 378px;
    margin: 40px;
    box-shadow: 0 2px 8px rgb(0 0 0 / 12%);
    background-color: #fff;
    .form-title {
      font-size: 16px;
      height: 68px;
      line-height: 68px;
      color: #585858;
      text-align: center;
      border-bottom: 1px solid #CDD7D5;
    }
    .login-form {
      padding: 24px 32px;
      .login-form-item {
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
        :deep(.el-form-item__label) {
          margin-bottom: 0 !important;
          line-height: 38px;
        }
      }
    }
  }
}
</style>
